<template>
    <div id="ememo-box">
        <div class="top" theme="light" ref="top">
            <div class="left">
                {{ titleData }}
            </div>
            <div class="item close" @click="quit">
                <svg width="13" height="13" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M8 8L40 40" stroke="#000000" stroke-width="4" stroke-linecap="round"
                        stroke-linejoin="round" />
                    <path d="M8 40L40 8" stroke="#000000" stroke-width="4" stroke-linecap="round"
                        stroke-linejoin="round" />
                </svg>
            </div>
            <div class="item ot" @click="ipcRenderer.send('toggleMin')">
                <svg width="13" height="13" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M10.5 24L38.5 24" stroke="#000000" stroke-width="4" stroke-linecap="round"
                        stroke-linejoin="round" />
                </svg>
            </div>

            <div class="item ot" @click="toggleTop" id="top" title="固定到最顶层">
                <svg width="13" height="13" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path
                        d="M41 18H19C18.4477 18 18 18.4477 18 19V41C18 41.5523 18.4477 42 19 42H41C41.5523 42 42 41.5523 42 41V19C42 18.4477 41.5523 18 41 18Z"
                        fill="none" stroke="#000000" stroke-width="4" stroke-linejoin="round" />
                    <path d="M9.96906 6H6V10.0336" stroke="#000000" stroke-width="4" stroke-linecap="round"
                        stroke-linejoin="round" />
                    <path d="M9.99705 30H6V26.012" stroke="#000000" stroke-width="4" stroke-linecap="round"
                        stroke-linejoin="round" />
                    <path d="M26.0023 6H30V10.0152" stroke="#000000" stroke-width="4" stroke-linecap="round"
                        stroke-linejoin="round" />
                    <path d="M16.0283 6H20.0083" stroke="#000000" stroke-width="4" stroke-linecap="round"
                        stroke-linejoin="round" />
                    <path d="M6 16C6 18.6536 6 19.9869 6 20" stroke="#000000" stroke-width="4" stroke-linecap="round"
                        stroke-linejoin="round" />
                    <path d="M30 16C30 18.6765 30 19.3456 30 18.0074" stroke="#000000" stroke-width="4"
                        stroke-linecap="round" stroke-linejoin="round" />
                    <path d="M15.9922 30H17.9996" stroke="#000000" stroke-width="4" stroke-linecap="round" />
                </svg>
            </div>

        </div>
        <div class="m" contenteditable spellcheck="false" id="editor" ref="editor">

        </div>
    </div>

</template>
<style scoped>
.top {
    width: 100%;
    height: 30px;
    -webkit-app-region: drag;
    transition: all 0.2s;
}

.top {
    background-color: #f1f3f9;
}


.top .left {
    float: left;
    height: 100%;
    width: calc(100% - 250px);
    padding-left: 10px;
    display: flex;
    align-items: center;
    font-size: 13px;
}

.top .item {
    width: 50px;
    height: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.1s;
    margin-left: 3px;
    -webkit-app-region: no-drag;
    cursor: pointer;
    float: right;
    transition: all 0.2s;
}


.top .close:hover {
    background-color: #c42b1c;
}

.top .close:active {
    background-color: #c84031;
}

.top .ot:hover {
    background-color: #e8e9ef;
}

.top .ot:active {
    background-color: #ebedf3;
}

.top .act {
    background-color: #e2e2e2;
}

html[class="mdui-theme-dark"] .top {
    background-color: #121212;
}

html[class="mdui-theme-dark"] .top svg {
    filter: blur() invert(1);
}

html[class="mdui-theme-dark"] .top .ot:hover {
    background-color: #373737;
}

html[class="mdui-theme-dark"] .top .ot:active {
    background-color: #4d4d4d;
}

html[class="mdui-theme-dark"] .top .act {
    background-color: #373737;
}





.m {
    width: calc(100% - 20px);
    height: calc(100% - 40px);
    position: fixed;
    top: 30;
    left: 0;
    outline: none;
    margin-left: 10px;
    margin-right: 10px;
    padding-top: 10px;
    overflow-x: hidden;
    overflow-y: auto;

    -moz-user-select: none;
    -o-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;
    transition: all 0.2s;
}
</style>
<style>
.m img {
    width: 40%;
    margin-left: 10px;
    border-radius: 10px;
    cursor: pointer;
}
</style>
<script setup>
import 'vditor/dist/index.css';
import { useRouter, onBeforeRouteLeave } from 'vue-router';
import { onMounted, ref } from 'vue';
import t from "@/assets/theme"
import { useIpcRenderer } from "@vueuse/electron";
import { snackbar } from "mdui/functions/snackbar.js";
import v from "@/assets/viewer.js"

v.vInit()
window.vShow = v.vShow
const ipcRenderer = useIpcRenderer();
const params = useRouter().currentRoute.value.params.id;
console.log(params);

let top = ref(null)

window.channel = new BroadcastChannel("ememo");
const settingChaneg = new BroadcastChannel("setting");
//const contentEditor = ref("");
let id
let title

let titleData = ref("")




let windowP
ipcRenderer.on("move", (event, arg) => {
    windowP = arg;

})

const toggleTop = () => {
    ipcRenderer.send("toggleTop")
    let t = document.getElementById("top");
    if (t.classList.contains("act")) {
        t.classList.remove("act")
    } else {
        t.classList.add("act")
    }
}

const quit = () => {
    ipcRenderer.on("change-content-memo", (event, arg) => {
        if (arg) {
            ipcRenderer.send('close')
        } else {
            snackbar({
                message: "保存失败",
            })
            setTimeout(() => ipcRenderer.send('close'), 1000)
        }
        // 清除监听
        ipcRenderer.removeAllListeners("change-content-memo")
    })
    ipcRenderer.send("change-content-memo", { id: id, content: document.getElementById("editor").innerHTML })
}

onMounted(() => {
    let setting = JSON.parse(localStorage.getItem("config"))["setting"];
    let fontS = setting.memo_font_size;
    let editor = document.getElementById("editor");

    top.value.setAttribute("theme", setting.theme);

    if (typeof params == "undefined") {  // 创建便签
        console.log("new");
        ipcRenderer.on("new-memo", (event, arg, data) => {
            if (!arg) {
                snackbar({
                    message: "程序异常",
                })
            } else {
                id = data.id;
                channel.postMessage("load");
                document.title = data.name
                title = data.name;
                editor.style.fontSize = fontS + "px";
                editor.style.fontFamily = `${setting.memo_font_en} , ${setting.memo_font_zh}`;
                titleData.value = data.name;
            }
            ipcRenderer.removeAllListeners("new-memo")
        })
        ipcRenderer.send("new-memo")
    } else {  // 打开便签
        ipcRenderer.on("get-memo", (event, arg, data, c) => {
            if (arg) {
                editor.innerHTML = data;
                id = +params;
                console.log(c);
                document.title = c.name
                title = c.name;
                editor.style.fontSize = fontS + "px";
                editor.style.fontFamily = `${setting.memo_font_en} , ${setting.memo_font_zh}`;
                titleData.value = c.name;
            } else {
                snackbar({
                    message: "程序异常",
                })
            }
            ipcRenderer.removeAllListeners("get-memo")
        })
        ipcRenderer.send("get-memo", +params)
    }




    editor.addEventListener("paste", (e) => {
        console.log("paste");
        event.preventDefault();

        var items = (event.clipboardData || window.clipboardData).items;
        for (var i = 0; i < items.length; i++) {
            if (items[i].type.indexOf("image") !== -1) {
                var blob = items[i].getAsFile();
                var reader = new FileReader();

                reader.onload = function (event) {
                    var img = document.createElement("img");
                    img.classList.add("img-paste");
                    img.src = event.target.result;
                    img.setAttribute("ondblclick", function () {
                        vShow(this.src)
                    }.toString().split(/\r?\n/).slice(1, -1).join('')
                    )
                    // 假设你有一个容器来放置图片  
                    editor.appendChild(img);
                };

                reader.readAsDataURL(blob);
            }
        }
        textPaste(e)
    })

    editor.addEventListener("dragenter", function (e) {  //拖进
        e.preventDefault();
    })
    editor.addEventListener("dragover", function (e) {  //拖来拖去 
        e.preventDefault();
    })
    editor.addEventListener('drop', function (event) {
        event.preventDefault();
        // 将类数组对象 转换成数组
        // var fileList = Array.from(event.dataTransfer.files);  //  es6 格式
        var fileList = [].slice.call(event.dataTransfer.files);  // es5 格式
        fileList.forEach(function (file) {
            // 读取文件
            var reader = new FileReader();
            reader.onload = function (e) {
                let data = e.target.result;
                let img = document.createElement("img");
                img.src = data;
                editor.appendChild(img);
            }
            reader.readAsDataURL(file);
        })
    })


    document.addEventListener('keydown', function (event) {
        // 是否按下esc
        if (event.keyCode === 27) {
            quit();
        }
        // 检查是否按下了Ctrl键  
        if (event.ctrlKey || event.metaKey) {
            // 检查是否按下了加号或减号键  
            if (event.key === '+') {
                console.log('Ctrl + was pressed');
                editor.style.fontSize = ++fontS + "px";
            } else if (event.key === '-') {
                console.log('Ctrl - was pressed');
                editor.style.fontSize = --fontS + "px";
            } else if (event.key === '0') {
                editor.style.fontSize = "30px";
                fontS = 30;
            } else if (event.key === 's') {
                ipcRenderer.on("change-content-memo", (event, arg) => {
                    if (!arg) {
                        console.log(id);
                        snackbar({
                            message: "程序异常",
                        })
                    } else {
                        console.log("ctrl + s");
                        let t = titleData.value
                        titleData.value = t + " - 已保存";
                        setTimeout(() => {
                            titleData.value = t;
                        }, 1000)
                    }
                    // 清除监听
                    ipcRenderer.removeAllListeners("change-content-memo")
                })
                ipcRenderer.send("change-content-memo", { id: id, content: document.getElementById("editor").innerHTML })
            }
        }
    });

    //setInterval(() => {
    //
    //    ipcRenderer.on("change-content-memo", (event, arg) => {
    //        if (!arg) {
    //            console.log(id);
    //            snackbar({
    //                message: "程序异常",
    //            })
    //        } else {
    //            let t = titleData.value
    //            titleData.value = t + " - 已保存";
    //            setTimeout(() => {
    //                titleData.value = t;
    //            }, 1000)
    //        }
    //    })
    //    ipcRenderer.send("change-content-memo", { id: id, content: document.getElementById("editor").innerHTML })
    //}, 20000)


    settingChaneg.onmessage = (ty) => {
        let data = JSON.parse(ty.data)



        console.log(data.theme);
        let nowTheme = t.getThemeType();
        console.log(nowTheme);

        let fontSi = data.memo_font_size;
        editor.style.fontSize = fontSi + "px";
        editor.style.fontFamily = `${data.memo_font_en} , ${data.memo_font_zh}`;
        ipcRenderer.on("get-mouse-loaction", (event, d) => {
            let x = d.x - windowP.x// - 120;
            let y = d.y - windowP.y// - 100;


            //let di = `<div style="position:fixed;left:${x}px;top:${y}px;width:3px;height:3px;background-color:red;z-index:999;border-radius:50%"></div>`
            //document.body.insertAdjacentHTML("beforeend", di);
            //console.log(x, y);
            //console.log(windowP.x, windowP.y);
            //console.log(data);
            if (data.theme == "auto") {
                let st = t.getSysTheme();
                if (nowTheme != st) {
                    console.log("设置主题 auto " + st);
                    //t.checkTheme(st, false)
                    t.changeTheme(st, true, { x: x, y: y })
                }
            } else {

                //console.log(data.theme);
                if (nowTheme != data.theme) {
                    console.log("设置主题 " + data.theme);
                    //t.checkTheme(data.theme, false)
                    t.changeTheme(data.theme, true, { x: x, y: y })
                }

            }


            //if (data.theme == "auto") {
            //    let systhe = t.getSysTheme();
            //    if (lastTheme != systhe) {
            //        console.log("设置主题 auto ");
            //
            //        t.changeTheme(systhe, true, { x: x, y: y })
            //
            //
            //    }
            //    top.value.setAttribute("theme", systhe)
            //} else {
            //    console.log(lastTheme, data.theme);
            //    //console.log(data.theme);
            //    console.log(lastTheme == data.theme);
            //
            //    if (lastTheme != data.theme) {
            //        console.log("设置主题 " + data.theme);
            //        t.changeTheme(data.theme, true, { x: x, y: y })
            //
            //    }
            //
            //    top.value.setAttribute("theme", data.theme)
            //}
            console.log("--------------------");

            // 清除监听
            ipcRenderer.removeAllListeners("get-mouse-loaction");
        })
        ipcRenderer.send("get-mouse-loaction");









    }



    //contentEditor.value = new Vditor('v', {
    //    height: "100%",
    //    toolbarConfig: {
    //        pin: true,
    //    },
    //    cache: {
    //        enable: false,
    //    },
    //    upload: {
    //        url: 'http://localhost:34787/upload', // 上传url
    //        accept: 'image/jpeg,image/png,image/gif,image/jpg,image/bmp', // 图片格式
    //        max: 2 * 1024 * 1024,  // 控制大小
    //        multiple: false, // 是否允许批量上传
    //        fieldName: 'file', // 上传字段名称
    //        // 文件名安全处理
    //        filename(name) {
    //            return name
    //                .replace(/[^(a-zA-Z0-9\u4e00-\u9fa5\.)]/g, '')
    //                .replace(/[\?\\/:|<>\*\[\]\(\)\$%\{\}@~]/g, '')
    //                .replace('/\\s/g', '');
    //        },
    //        // 数据转换
    //        format(files, responseText) {
    //            return responseText;
    //        },
    //    },
    //
    //    toolbar: ["emoji", "headings", "bold", "italic", "strike", "|", "list", "ordered-list", "check", "code", "inline-code", "line", "|", "table", "quote", "link", "|", "undo", "redo", "fullscreen", "preview", "edit-mode", "export"],
    //    after: () => {
    //        ipcRenderer.on("get-memo", (event, data) => {
    //            contentEditor.value.setValue(data);
    //        });
    //        ipcRenderer.send("get-memo", params);
    //        let config = JSON.parse(localStorage.getItem("config"));
    //        let theme = config.setting.theme;
    //        if (theme == "auto") {
    //            let syet = t.getSysTheme();
    //            contentEditor.value.setTheme(syet, syet);
    //        } else {
    //            contentEditor.value.setTheme(theme, theme);
    //        }
    //        let last;
    //        let n = 0;
    //        time = setInterval(() => {
    //            n++;
    //            if (n === 1) {
    //                last = contentEditor.value.getValue();
    //                ipcRenderer.send("update-memo", {
    //                    name: params,
    //                    data: contentEditor.value.getValue()
    //                });
    //            } else {
    //                if (last !== contentEditor.value.getValue()) {
    //                    changeTitle();
    //                    ipcRenderer.send("update-memo", {
    //                        name: params,
    //                        data: contentEditor.value.getValue()
    //                    });
    //                }
    //                last = contentEditor.value.getValue();
    //            }
    //        }, 5000);
    //    },
    //});
});

//const back = () => {
//    isNavigating = true; // 设置标志位
//    clearInterval(time);
//    ipcRenderer.send("update-memo", {
//        name: params,
//        data: contentEditor.value.getValue()
//    });
//    snackbar({
//        message: "保存成功",
//    });
//    router.go(-1);
//};
//
//const changeTitle = () => {
//    let title = document.title;
//    document.title = title + " - 保存成功";
//    setTimeout(() => {
//        document.title = title;
//    }, 1000);
//};

//onBeforeRouteLeave((to, from, next) => {
//    if (isNavigating) {
//        next(); // 允许导航
//    } else {
//        confirm({
//            headline: "是否保存",
//            description: "您正在跳转到" + to.path + "，为了确保数据安全，请保存.",
//            confirmText: "保存",
//            cancelText: "取消跳转",
//            onConfirm: () => {
//                clearInterval(time);
//                ipcRenderer.send("update-memo", {
//                    name: params,
//                    data: contentEditor.value.getValue()
//                });
//                snackbar({
//                    message: "保存成功",
//                });
//                next();
//            },
//            onCancel: () => next(false),
//        });
//    }
//});

function textPaste(event) {
    var text;
    var clp = (event.originalEvent || event).clipboardData;
    // 兼容针对于opera ie等浏览器
    if (clp === undefined || clp === null) {
        text = window.clipboardData.getData("text") || "";
        if (text !== "") {
            if (window.getSelection) {
                // 针对于ie11 10 9 safari
                var newNode = document.createElement("span");
                newNode.innerHTML = text;
                window.getSelection().getRangeAt(0).insertNode(newNode);
            } else {
                // 兼容ie10 9 8 7 6 5
                document.selection.createRange().pasteHTML(text);
            }
        }
    } else {
        // 兼容chorme或hotfire
        text = clp.getData('text/plain') || "";
        if (text !== "") {
            document.execCommand('insertText', false, text);
        }
    }
}
</script>
